import {createAsyncThunk} from "@reduxjs/toolkit";

import {ReimburseType} from "type/ReimburseType";
import {requestDelete, requestGet, requestPost, requestPut} from "util/request";
import LogFactory from "log/LogFactory";
import {Page, PagingData} from "type/Page";

const log = LogFactory.getLog("reimburseAsyncAction") ;

/**
 * 更新报销单总金额和条目数量返回值类型
 */
interface FetchUpdateTotalAmountResult {
    /**
     * 根据报销单信息的结果数量
     */
    data: number
    /**
     * 报销单信息
     */
    reimburse: ReimburseType;
}

export const fetchPageData = createAsyncThunk(
    'reimburse/fetchPageData',
    async (paging: PagingData) => {
        const response = await requestGet<Page<ReimburseType>>(`/record/reimburse/page/${paging.current}/${paging.pageSize}`) ;
        return response.data ;
    }
) ;


/**
 * 更新报销单总金额和条目数量,根据报销单id
 */
export const fetchUpdateTotalAmount = createAsyncThunk(
    'reimburse/fetchUpdateTotalAmount',
    async (reimburse: Partial<ReimburseType>): Promise<FetchUpdateTotalAmountResult> => {
        const response = await requestPost<number>("/record/reimburse",reimburse) ;
        return {data: response.data, reimburse: reimburse as ReimburseType } ;
    }
) ;

/**
 * 添加报销单
 */
export const fetchAddReimburse = createAsyncThunk(
    'reimburse/fetchAddReimburse',
    async (reimburse: ReimburseType) => {
        log.request("添加报销单: ", reimburse) ;
        return await requestPut<ReimburseType>("/record/reimburse/add-query",reimburse) ;
    }
) ;

/**
 * 删除报销单,根据id
 */
export const fetchDeleteReimburse = createAsyncThunk(
    'reimburse/fetchDeleteReimburse',
    async (id: number): Promise<{data: number ,id: number}> => {
        log.request("删除报销单: ", id) ;
        let res = await requestDelete<number>("/record/reimburse/" + id) ;
        return {
            data: res.data ,
            id: id
        } ;
    }
) ;

/**
 * 更新报销单
 */
export const fetchUpdateReimburse = createAsyncThunk(
    'reimburse/fetchUpdateReimburse',
    async (reimburse: ReimburseType): Promise<{ data: number,reimburse: ReimburseType }> => {
        log.request("更新报销单: ", reimburse) ;
        let res = await requestPost<number>("/record/reimburse",reimburse) ;
        return {
            data: res.data,
            reimburse: reimburse
        };
    }
) ;